% eccentric102
% 3 stage block design 1)fixation 2)short saccades 1)fixation 3)long saccades  
% bcoe@biomed.queensu.ca
clc; 
clear;
close all;
RecordStart=132; % for IScan
RecordStop=136;  % for IScan
% today=[num2str(c(1)) '-' num2str(c(2)) '-' num2str(c(3)) ];
% if today(7)=='-'
%     today=[today(1:5), '0',today(6:end)];
% end
% if length(today)==9;
%     today=[today(1:8), '0',today(9:end)];
% end
try % prometheus
    home_folder='e:\Data\randomwalk';
    cd(home_folder)
catch %mri stimulus computer
    home_folder='C:\_User\_bcoe\Data\randomwalk';
    cd(home_folder)
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%   ASSIGN PARAMETERS   %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% First, try to load table of parameter names and set values
try % this should speed things along if your running a few studies on the same subject
    load('temp')
    for par = 1:size(Parameters,1)% assign each parameter in the table to its value
        eval([Parameters{par,1} '=''' Parameters{par,2} ''';']); % for string entries
    end   
    sub_inits;% check if it exists
    if ~strcmp(kyou,standard_date(2))% check if it exists & ...
        error;% if today's date doesn't match the date in the temp file force 'try' to fail
    end   
    file_nb=str2num(file_nb)+1;% check if it exists & increment
    if file_nb<10
        file_nb=['0' num2str(file_nb)];        
    else
        file_nb=num2str(file_nb);
    end
    prescan_time; % check if it exists
    TR;
    tsat_scans;
    abab;%=num2str(abs(str2num(abab)-2)+1);
        sac_dur;
    fix_dur;

catch % else start from scratch
    beep
    sub_inits='XXX';
    kyou=standard_date(2);
    file_nb='00';
    prescan_time='0'; % 
    TR='3000';
    tsat_scans='2';  %T1 saturation scans
    abab='1';
    sac_dur='30000';
    fix_dur='15000';
end

Parameters={% variable  value           'discription'                           string or number?
    'sub_inits',	sub_inits,		'Subjects 3 Initials (ABC)',            's';...
        'kyou',		    kyou,		    'Today''s Date (yyyy-mm-dd)',           's';...
        'file_nb',		file_nb,		'File # (or run #, always 2 digits):',  's';...
        'prescan_time',	prescan_time,	'Prescan Normalization Time (in secs, 0 = wait for MR trigger)', 'n';...
        'TR',	        TR,          	'TR (in millisecs)',                    'n';...
        'tsat_scans',	tsat_scans, 	'# of T1 saturation scans (in TR)',     'n';...
        'abab',	        abab, 	        'ABABA, BABAB, ABAB, BABA (1, 2, 3, or 4)',              'n';...
        'sac_dur',	    sac_dur,        'Duration of Saccade blocks (in ms or "TR*n" )',   'n';...
        'fix_dur',	    fix_dur,        'Duration of Fixation blocks (in ms or "TR*n" )',  'n';...
    };

save('temp','Parameters');    % saves temp data (still in string format)

S_WAIT =1; t_state{S_WAIT }='WAIT';
S_TSAT =2; t_state{S_TSAT }='T1SAT';  
S_FIX  =3; t_state{S_FIX  }='FIX';  
S_LWALK=4; t_state{S_LWALK}='LeftWalk';  
S_RWALK=5; t_state{S_RWALK}='RightWalk';  

update=1;
while update
    %now set the numeric data to numbers
    for par= 1:length(Parameters) 
        if Parameters{par,4}=='n'
            eval([Parameters{par,1} '=' Parameters{par,2} ';']); % for numeric entries
        end
    end
    number_o_block=14+2;% 2 = prescan time & t saturation scans
    duration_o_block(S_WAIT)=prescan_time*1000;% magnet prescan time (min 3sec but )????????
    duration_o_block(S_TSAT)=tsat_scans*TR;% dummy or T1 saturation scans
    duration_o_block(S_FIX)=round(fix_dur/TR)*TR;
    duration_o_block(S_RWALK)=round(sac_dur/TR)*TR;
    duration_o_block(S_LWALK)=round(sac_dur/TR)*TR;
    
    if prescan_time>0
        time_ting=[S_WAIT S_TSAT];
    else    
        time_ting=[S_TSAT];
    end
    switch abab
        case 1
            for i= 1:(number_o_block-2)/4
                time_ting=[time_ting S_LWALK S_FIX S_RWALK S_FIX ];
            end
            time_ting=[time_ting S_LWALK S_FIX ];
        case 2
            for i= 1:(number_o_block-2)/4
                time_ting=[time_ting  S_RWALK S_FIX S_LWALK S_FIX];
            end
            time_ting=[time_ting S_RWALK S_FIX ];
        case 3
            for i= 1:(number_o_block-2)/4
                time_ting=[time_ting S_LWALK S_FIX S_RWALK S_FIX ];
            end
        case 4
            for i= 1:(number_o_block-2)/4
                time_ting=[time_ting  S_RWALK S_FIX S_LWALK S_FIX];
            end
    end
    time_ting';
    next_time=cumsum([0 duration_o_block(time_ting)])';
    t_state(time_ting)';
    next_state=time_ting;
    
    clc;
    fprintf('%s \n',['Duration of Paragigm: ' num2str(max(next_time)) 'ms or ' num2str(floor(max(next_time)/60000)) ':' num2str(rem((max(next_time)/60000)*60,60)) 'min.'])
    fprintf('%s \n',['Total # of Volumes: ' num2str((max(next_time)-(prescan_time*1000))/TR)  ])
    fprintf('%s \n',['TR=' num2str(TR) ',  prescan_time=' num2str(prescan_time)])
    fprintf('%s \n',['(' num2str((max(next_time)-(prescan_time*1000))/TR) '*TR)+(prescan_time*1000)=' num2str(eval(['(' num2str((max(next_time)-(prescan_time*1000))/TR) '*TR)+(prescan_time*1000)']))]);
    fprintf('%s \n','# State: Onset:  Dur:  TR''s: ')
    for i=1 :length(time_ting)
        spacea='';spacea(1:10-length(t_state{time_ting(i)}))=' ';
        spaceb='';spaceb(1:7-length(num2str(next_time(i))))=' ';
        spacec='';spacec(1:7-length(num2str(duration_o_block(time_ting(i)))))=' ';
        spaced='';spaced(1:5-length(num2str(duration_o_block(time_ting(i))/TR) ))=' ';
        fprintf('%s \n',[num2str(time_ting(i)) ': '  t_state{time_ting(i)} spacea spaceb num2str(next_time(i)) spacec num2str(duration_o_block(time_ting(i))) spaced num2str(duration_o_block(time_ting(i))/TR) ])
    end
    if update % so reload the text version of the data if need to update.
        load('temp') 
    end
    [ParamInputs update] = inputdlg_offscreen(Parameters(:,3), 'Enter Parameters', 1, Parameters(:,2));
    if isempty(ParamInputs);
        disp('Task Canceled');
        return
    end
    [Parameters{:,2}] = deal(ParamInputs{:});
    % save data file
    folder=[Parameters{1,2} '.' Parameters{2,2}];
    if ~exist(folder,'dir')
        eval(['mkdir ' folder]);
    end
    eval(['cd ' folder]);
    file_name=[Parameters{1,2} '.' Parameters{2,2} '_' Parameters{3,2} '.mat'];
    if exist(file_name,'file')
        yesno=questdlg_offscreen('File Exits! Overwrite it?','Be Careful!','Yes','No','No');
        if yesno(1)=='N'
            disp(['File Exists: ' file_name])
            update=1;
            file_nb=str2num(file_nb)+1;% increment
            if file_nb<10
                file_nb=['0' num2str(file_nb)];        
            else
                file_nb=num2str(file_nb);
            end
            Parameters{3,2}=file_nb;
        end
        clear yesno;
    end
    cd(home_folder)
    save('temp','Parameters');    % saves temp data (still in string format)
end
%now set the numeric data to numbers
for par= 1:length(Parameters) 
    if Parameters{par,4}=='n'
        eval([Parameters{par,1} '=' Parameters{par,2} ';']); % for numeric entries
    end
end
number_o_block=14+2;% 2 = prescan time & t saturation scans
duration_o_block(S_WAIT)=prescan_time*1000;% magnet prescan time (min 3sec but )????????
duration_o_block(S_TSAT)=tsat_scans*TR;% dummy or T1 saturation scans
duration_o_block(S_FIX)=round(fix_dur/TR)*TR;
duration_o_block(S_RWALK)=round(sac_dur/TR)*TR;
duration_o_block(S_LWALK)=round(sac_dur/TR)*TR;

if prescan_time>0
    time_ting=[S_WAIT S_TSAT];
else    
    time_ting=[S_TSAT];
end
switch abab
    case 1
        for i= 1:(number_o_block-2)/4
            time_ting=[time_ting S_LWALK S_FIX S_RWALK S_FIX ];
        end
        time_ting=[time_ting S_LWALK S_FIX ];
    case 2
        for i= 1:(number_o_block-2)/4
            time_ting=[time_ting  S_RWALK S_FIX S_LWALK S_FIX];
        end
        time_ting=[time_ting S_RWALK S_FIX ];
    case 3
        for i= 1:(number_o_block-2)/4
            time_ting=[time_ting S_LWALK S_FIX S_RWALK S_FIX ];
        end
    case 4
        for i= 1:(number_o_block-2)/4
            time_ting=[time_ting  S_RWALK S_FIX S_LWALK S_FIX];
        end
end
time_ting';
next_time=cumsum([0 duration_o_block(time_ting)])';
t_state(time_ting)';
next_state=time_ting;
clc;
fprintf('%s \n',['Duration of Paragigm: ' num2str(max(next_time)) 'ms or ' num2str(floor(max(next_time)/60000)) ':' num2str(rem((max(next_time)/60000)*60,60)) 'min.'])
fprintf('%s \n',['Total # of Volumes: ' num2str((max(next_time)-(prescan_time*1000))/TR)  ])
fprintf('%s \n',['TR=' num2str(TR) ',  prescan_time=' num2str(prescan_time)])
fprintf('%s \n',['(' num2str((max(next_time)-(prescan_time*1000))/TR) '*TR)+(prescan_time*1000)=' num2str(eval(['(' num2str((max(next_time)-(prescan_time*1000))/TR) '*TR)+(prescan_time*1000)']))]);
fprintf('%s \n','# State: Onset:  Dur:  TR''s: ')
for i=1 :length(time_ting)
    spacea='';spacea(1:10-length(t_state{time_ting(i)}))=' ';
    spaceb='';spaceb(1:7-length(num2str(next_time(i))))=' ';
    spacec='';spacec(1:7-length(num2str(duration_o_block(time_ting(i)))))=' ';
    spaced='';spaced(1:5-length(num2str(duration_o_block(time_ting(i))/TR) ))=' ';
    fprintf('%s \n',[num2str(time_ting(i)) ': '  t_state{time_ting(i)} spacea spaceb num2str(next_time(i)) spacec num2str(duration_o_block(time_ting(i))) spaced num2str(duration_o_block(time_ting(i))/TR) ])
end

eval(['cd ' folder]);



c=define_colors(256);
c.BACKGROUND=c.BLACK;
c.GO=c.GREEN;
c.NG=c.RED;
% Number of Locations
% 135  90  45
% 180  +  360
% 225 270 315
% angle of 0 means ecc of 0 and vice versa!
loc_AngEcc=[];
%loc_AngEccb =	[ 5 8.5; 175 8.5; 185 8.5; 355 8.5];    % ang & ecc positions. only change this line!!!
%loc_AngEcc =	[ 5 1.5; 175 1.5; 185 1.5; 355 1.5];    % ang & ecc positions. only change this line!!!
% loc_AngEcc =	[ 5 .75; 175 .75; 185 .75; 355 .75];    % ang & ecc positions. only change this line!!!
% loc_AngEcc =	[ 360 8; 360 7; 360 6; 360 5; 360 4; 360 3; 360 2; 360 1; 0 0; 180 1;180 2;180 3;180 4;180 5;180 6;180 7;180 8;];  


loc_AngEcc(1,1:41)=360;
loc_AngEcc(2,1:41)=-8:.4:8;
loc_AngEcc=loc_AngEcc';
% ang & ecc positions. only change this line!!!
%loc_AngEcc=	[ 360 12; 180 12; ];    % ang & ecc positions. only change this line!!!
n_loc=length(loc_AngEcc);
loc_XY=[]; 
[ loc_XY(:,1) loc_XY(:,2)]=polar2cart(loc_AngEcc(:,1),loc_AngEcc(:,2),1);   
%loc_XYb=[]; 
%[ loc_XYb(:,1) loc_XYb(:,2)]=polar2cart(loc_AngEccb(:,1),loc_AngEccb(:,2),1);   
%loc_XYm=[]; 
%[loc_XYm(:,1) loc_XYm(:,2)]=polar2cart(loc_AngEcc(:,1),loc_AngEcc(:,2)+.6,1);  % the +.6 is for the width of the targtes which may have to be changed 
%loc_XY(:,2)=-loc_XY(:,2); % reverse vertical for robarts eyeview

screenRect=get(0,'ScreenSize');
c_x=screenRect(3)/2;
c_y=screenRect(4)/2;

% for now....
dist2screen=145;
screenwidth=46;
if dist2screen*screenwidth
    [ang ecc]=cart2polar(dist2screen,screenwidth/2);
else
    ang=30;
end	
pixperdeg=floor(screenRect(3)/(ang*2));
stim_size=.1;% radius of stim
s_circle=[-1 -1	1 1]*pixperdeg*stim_size;      						% stimulus circle
fix_b=floor([c_x c_y c_x c_y]+([-1 -1	1 1]*pixperdeg*(stim_size/4.5)));	% fixation middle
fix_a=floor([c_x c_y c_x c_y]+([-1 -1	1 1]*pixperdeg*stim_size));	% fixation circle

pixloc_XY=[];
pixloc_XY (:,1)=(loc_XY (:,1)*pixperdeg)+c_x;% set ang&ecc to x&y based on screen size
pixloc_XY (:,2)=(loc_XY (:,2)*pixperdeg)+c_y;
%pixloc_XYb(:,1)=(loc_XYb(:,1)*pixperdeg)+c_x;% set ang&ecc to x&y based on screen size
%pixloc_XYb(:,2)=(loc_XYb(:,2)*pixperdeg)+c_y;
for i=1:n_loc
    tgt_rect1(i,:)=floor([pixloc_XY(i,:) pixloc_XY(i,:)]+s_circle); % for use with mac's LeToRiBo rect shite
    %    tgt_rect2(i,:)=floor([pixloc_XYb(i,:) pixloc_XYb(i,:)]+(s_circle*1.20)); % for use with mac's LeToRiBo rect shite
end

% % axis(screenRect([1 3 2 4]))
% %  axis ij
% plot(tgt_rect(:,1),tgt_rect(:,4),'o')
% plot(tgt_rect(:,3),tgt_rect(:,4),'o')
% plot(tgt_rect(:,1),tgt_rect(:,2),'o')
% plot(tgt_rect(:,3),tgt_rect(:,2),'o')

A=[];
A.file_name=[Parameters{1,2} '.' Parameters{2,2} '_' Parameters{3,2}];
A.clock=round(clock);
A.parameters=Parameters;
A.ang_ecc=loc_AngEcc;
A.t_state=t_state;
A.pixperdeg=pixperdeg;
A.screenRect=screenRect;
A.colors=c;

clc;
simpleserial('close');
simpleserial('open','com1',115200);
if simpleserial('bytesready')==0,pause(.1),clc,pause(.1); fprintf('\n\n%s \n','please check ''Track Active'' ');end
while simpleserial('bytesready')==0 
    [keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
    if keyCode(27)% ESC on pcwin
        simpleserial('close');
        disp('Task Aborted');
        return
    end    

end
[w,screenRect] = SCREEN(0,'OpenWindow',0,[],32);
pause(.01)
SCREEN(w,'fillrect',c.BACKGROUND); 
[buffer,rect]  = SCREEN(0,'OpenOffscreenWindow',0,[],32);
SCREEN(buffer,'fillrect',c.BACKGROUND); 
SCREEN(w,'TextStyle',1);% 0=plain, 1=bold, 2=italics, 3=1&2,  4=underlined, 5=4&1,6=4&2, 7=4&3. rem(?,8)
[oldFontName,oldFontNumber]=SCREEN(w,'TextFont','Tahoma');
SCREEN(w,'TextSize',40);
ttext='Waiting for the MRI to start';
twidth=SCREEN(w,'TextWidth',ttext);
SCREEN(w,'DrawText',ttext,c_x-(twidth/2),c_y-100,c.GREEN);
SCREEN(w,'TextSize',40);
screen(w,'waitblanking');
refresh=getsecs;
screen(w,'waitblanking',10);
refresh=(getsecs-refresh)/10*1000;
A.refresh=refresh;
index=0;
%state=S_FIX;
if prescan_time>0
    status=S_WAIT;
else
    status=S_TSAT;
end

%target=tgt_rect(1,:);

SCREEN(buffer,'fillrect',c.BACKGROUND); 
buttons=0; % prevent from skipping mouse button loop
while buttons(1)==0  
    warning off MATLAB:DeprecatedLogicalAPI;
    [keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
    warning on MATLAB:DeprecatedLogicalAPI;
    keyCode=min(find(keyCode));
    if keyCode==27% ESC on pcwin
        SCREEN('Closeall');
        simpleserial('close');
        disp('Task Aborted');
        return
    end    
    if keyCode==48+5% '5%' on pcwin the new mri trigger
        buttons=1;
    end    
end
abs_start_time=floor(getsecs*1000);
simpleserial('write', char(RecordStart)); % for IScan
clc;
screen(w,'waitblanking',3);
SCREEN('CopyWindow',buffer,w);
HideCursor;
%pause(TR*3)
buttons=0; % prevent from skipping mouse button loop
switch abab
    case 1
        next_tgt=n_loc;
    case 2
        next_tgt=1;
    case 3 
        next_tgt=n_loc;
    case 4
        next_tgt=1;
end
next_time=next_time+abs_start_time;
next_TR=1;
report=1;
while status
    index=index+1;
    status=next_state(index);
    state(index)=status;
    switch status     
        case S_WAIT % initial wait peroid
            SCREEN(buffer,'filloval',c.ORANGE,tgt_rect1(next_tgt,:));  % draw fix            
            %status=S_LWALK;
        case S_TSAT % T1 saturation scans
            SCREEN(buffer,'filloval',c.RED,tgt_rect1(next_tgt,:));  % draw fix            
            %status=S_LWALK;
        case S_FIX % fixation
            SCREEN(buffer,'filloval',c.RED,tgt_rect1(next_tgt,:));  % draw fix            
        case S_RWALK % near target
            %SCREEN(buffer,'filloval',c.GREEN,fix_a);  % draw fix
            next_tgt=1;this_tgt=1;
            increment=1;
            tgt_rect=tgt_rect1;
            %status=S_FIX;
        case S_LWALK % far target
            %SCREEN(buffer,'filloval',c.GREEN,fix_a);  % draw fix
            next_tgt=n_loc;this_tgt=n_loc;
            increment=-1;
            tgt_rect=tgt_rect1;
            %status=S_FIX;
    end %switch status     
    
    screen(w,'waitblanking');
    SCREEN('CopyWindow',buffer,w);
    simpleserial('write', char(state)); % for IScan

    s_time(index)=floor(getsecs*1000);
    tgt_switch=s_time(index);
%     next_tgt=0;
%     this_tgt=1;
    buttons=0; % prevent from skipping mouse button loop
    tgt_switch=floor(getsecs*1000)+800+(refresh*((ceil(rand*5)-3)*6));
    tgt_duration=floor(getsecs*1000)+floor(getsecs*1000); %force to be impossible first time around
    while buttons(1)==0  & floor(getsecs*1000) < next_time(index+1); %state_time(index)
        if floor(getsecs*1000)>=report+1000 | next_TR==ceil((report-abs_start_time)/TR)
            clc;
            next_TR=ceil((report-abs_start_time)/TR)+1;
            report=floor(getsecs*1000);
            fprintf('%s \n',['   State: ' t_state{state(index)} ]);
            fprintf('%s \n',['      TR: ' num2str(ceil((report-abs_start_time)/TR))]);
            fprintf('%s \n',['    Time: ' num2str(floor((report-abs_start_time)/1000))]);
            fprintf('%s \n',['NextTime: ' num2str(floor((next_time(index+1)-abs_start_time)/1000))]);
            fprintf('%s \n',['Remaning: ' num2str(ceil(((next_time(index+1)-abs_start_time)/1000)-((report-abs_start_time)/1000)))]);
        end         
%         if floor(getsecs*1000) > next_time(index)+250;% accept no mouse clicks for 250ms;
%             [x y buttons]=getmouse;
%         end
        if state(index)>S_FIX & floor(getsecs*1000)>=tgt_duration
            screen(w,'waitblanking');
            SCREEN('CopyWindow',buffer,w);
            simpleserial('write', char(state)); % for IScan
        end
        if state(index)>S_FIX & floor(getsecs*1000)>=tgt_switch
            %tgt_switch=floor(getsecs*1000)+600+(refresh*((ceil(rand*5)-3)*6));
            tgt_switch=floor(getsecs*1000)+(duration_o_block(state(index))/(n_loc+1))+(refresh*((ceil(rand*5)-3)*6));

%             tgt_duration=floor(getsecs*1000)+100; % duration of the tgt or fixation spot = 120ms
%             SCREEN(buffer,'fillrect',c.BACKGROUND);  % erase all            
            
%             switch next_tgt>0
%                 case 1 % tgt 1
                    SCREEN(buffer,'fillrect',c.BACKGROUND);  % erase all            
                    SCREEN(buffer,'filloval',c.GREEN,tgt_rect(next_tgt,:));  % draw target
                    this_tgt=next_tgt;
                    next_tgt=next_tgt+increment; 
                    if next_tgt<=0 ,next_tgt=1;end
                    if next_tgt>=n_loc+1 ,next_tgt=n_loc;end
%                     if next_tgt<=0 ,next_tgt=n_loc;end
%                     if next_tgt>=n_loc+1 ,next_tgt=1;end
                    
%                 case 2 % tgt 2
%                     SCREEN(buffer,'filloval',c.GREEN,tgt_rect(2,:));  % draw target
%                     next_tgt=0; this_tgt=2;
%                 case 0 % fix
%                     SCREEN(buffer,'filloval',c.GREEN,fix_a);  % draw fix
%                     %next_tgt=abs(((this_tgt-2))-1);  
%                     temp=1:n_loc; 
%                     temp(this_tgt)=n_loc+1;% to avoid repetition of last tgt
%                     temp(rem((this_tgt)+1,4)+1)=n_loc+1;% to avoid 2/3 preferential selection of switching sides. only works for 4 tgts
%                     temp(temp==n_loc+1)=[];
%                     next_tgt=temp(ceil(rand*(length(temp)))); 
%             end
            screen(w,'waitblanking');
            SCREEN('CopyWindow',buffer,w);
            simpleserial('write', char(state)); % for IScan
            SCREEN(buffer,'fillrect',c.BACKGROUND);  % preemptivly erase all
        end % state(index)==S_TGT & floor(getsecs*1000)>=tgt_switch+500
        
        warning off MATLAB:DeprecatedLogicalAPI;
        [keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
		warning on MATLAB:DeprecatedLogicalAPI;
		if keyCode(27)% ESC on pcwin
			buttons=1; % get out of this loop 
            status=0;% get out of status loop
        end
    end % while buttons(1)==0  & getsecs < next_time(index) %state_time(index) 
    e_time(index)=floor(getsecs*1000);
    if status, buttons=0; end% prevent from skipping mouse button loop
    if index+1>=length(next_time);
        status=0;
    end
end % while status
simpleserial('write', char(RecordStop)); % for IScan
simpleserial('close');

if buttons<1, pause(2); end % just to add a bit of buffer unless esc is pressed
A.s_time=s_time-abs_start_time;
A.e_time=e_time-abs_start_time;
A.state=state;
save([A.file_name '.mat'],'A');
disp(['Saved file: ' A.file_name '.mat']);
SCREEN(w,'fillrect',c.BACKGROUND);
temp=(c.M_GREY-c.BACKGROUND)./60;
for i = 1:60 % fade to ?_GREY algorythm
    SCREEN(w,'fillrect',round(c.BACKGROUND+(temp*i)));
    screen(w,'waitblanking');
end    

SCREEN(w,'TextStyle',1);% 0=plain, 1=bold, 2=italics, 3=1&2,  4=underlined, 5=4&1,6=4&2, 7=4&3. rem(?,8)
[oldFontName,oldFontNumber]=SCREEN(w,'TextFont','Tahoma');
SCREEN(w,'TextSize',58);
ttext='thank you!';
twidth=SCREEN(w,'TextWidth',ttext);
SCREEN(w,'DrawText',ttext,c_x-(twidth/2),c_y-60,c.BLUE);
ttext='please rest.';
twidth=SCREEN(w,'TextWidth',ttext);
SCREEN(w,'DrawText',ttext,c_x-(twidth/2),c_y+60,c.BLUE);
SCREEN(w,'TextSize',40);
buttons=0;
while buttons(1)==0 
    %[x y buttons]=getmouse;
    warning off MATLAB:DeprecatedLogicalAPI;
    [keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
    warning on MATLAB:DeprecatedLogicalAPI;
    if sum(keyCode)% ESC on pcwin
        buttons=1; % get out of this loop 
        status=0;% get out of status loop
    end
end
showcursor;
SCREEN(w,'Close');
SCREEN(buffer,'Close');
cd
dir